/* File:	PrimeGenerator.m - Prime generator for 'PrimeSpiral'
 *
 * By:		Christopher Lane
 *		Symbolic Systems Resources Group
 *		Knowledge Systems Laboratory
 *		Stanford University
 *
 * Date:	24 February 1990
 *
 * Copyright:	1990 by The Leland Stanford Junior University.  This program
 *		may be distributed without restriction for non-commercial use.
 */

#import <stdlib.h>
#import <stdio.h>

#import "PrimeGenerator.h"

@implementation PrimeGenerator

+ new
{
	self = [super new];
	
	if ((primes = (ENTRY *) calloc((maximum = NUMELEMS), sizeof(ENTRY))) == NULL) {
		perror("calloc");
		exit(EXIT_FAILURE);
		}
		
	index = 0;
	number = 1;
	
	return self;
}
	
- (unsigned int) generate
{
	register unsigned int i;
	
	if (number > 2) {
loop:	for (i = 1, number += 2; i < index && number >= primes[i].square; i++)
			if (number == primes[i].square || (number % primes[i].prime) == 0) goto loop;
		}
	else number++;
	primes[index].prime = number;
	primes[index].square = number * number;
	if (++index == maximum) {
#ifdef DEBUG
		(void) printf("Maximum (%d) primes exceeded, resizing.\n", maximum);
#endif
		if ((primes = (ENTRY *) realloc((void *) primes, (maximum += NUMELEMS) * sizeof(ENTRY))) == NULL) {
			perror("realloc");
			exit(EXIT_FAILURE);
			}
		}
#ifdef DEBUG
	(void) printf("%d", number);
#endif
	return (number);
}

- free
{
	if (primes != NULL) cfree((void *) primes);
	return [super free];
}

@end
